<?php
/**
 * Unified API Handler
 * Handles all API requests: cart, newsletter, etc.
 */
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

$endpoint = $_GET['endpoint'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

if ($endpoint === 'cart-count') {
    if (isLoggedIn()) {
        $cart_items = getCartItems($pdo, $_SESSION['user_id']);
        echo json_encode(['count' => count($cart_items)]);
    } else {
        echo json_encode(['count' => 0]);
    }
    exit;
}

if ($endpoint === 'newsletter') {
    $email = $input['email'] ?? $_POST['email'] ?? '';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => 'Invalid email']);
        exit;
    }
    try {
        $stmt = $pdo->prepare("INSERT INTO newsletter_subscribers (email) VALUES (?)");
        $stmt->execute([$email]);
        echo json_encode(['success' => true, 'message' => 'Subscribed successfully']);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Already subscribed']);
    }
    exit;
}

// If no endpoint matches, redirect
http_response_code(404);
echo json_encode(['success' => false, 'message' => 'Endpoint not found']);

